<template>
    <div>
        <el-collapse model-value="1" class="collapase-main">
            <el-collapse-item :title="title" name="1" class="collapsebg">
                <div v-if="dataList.length > 0" class="tree-main">
                    <el-tree
                        ref="treeTemplate"
                        show-checkbox
                        :data="dataList"
                        node-key="id"
                        check-strictly
                        :default-expand-all="true"
                        :render-after-expand="false"
                        :render-content="renderContent"
                        style="width: 100%"
                        clearable
                        @check-change="handleCheckChange"
                    />
                </div>
                <div v-else class="nodata">
                    暂无数据
                </div>
            </el-collapse-item>
        </el-collapse>
    </div>
</template>
<script setup lang="ts">
import { ref, PropType, computed } from 'vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { ElTree, ElMessage, ElIcon } from 'element-plus'

const props = defineProps({
    title: {
        type: String,
		default: ''
    },
    dataList: {
        type: Array as PropType<any[]>,
		default: () => []
    }
})

const emit = defineEmits(['checked'])
interface Tree {
  id: number
  label: string
  children?: Tree[],
  number: string | Number
}
const renderContent = (
  h: any,
  {
    node,
    data,
    store,
  }: {
    node: Node
    data: Tree
    store: Node['store']
  }
) => {
    return h('span', {}, [node.label + '(' + data.number + ')']);
}
const treeTemplate = ref<InstanceType<typeof ElTree>>()
const tags = computed(()=>{
    emit('checked', treeTemplate.value?.getCheckedKeys(false))
    return treeTemplate.value?.getCheckedNodes(false, false)
})
interface CheckData {
    label: string;
    id: string | number;
}
const handleCheckChange = (data: CheckData) => {
    if (!Array.isArray(tags.value)) return; // 确保 tags.value 是数组
    const newArr = tags.value;
    let index = newArr.findIndex((item) => item.name === data.label);
    if (index !== -1) {
        newArr.splice(index, 1);
    } else {
        newArr.push({ name: data.label, id: data.id, label: data.label });
    }
};
</script>
<style lang="scss" scoped>
.nodata {
    text-align: center;
    padding-top: 1.3rem;
    cursor: pointer;
    color: #a8abb2;
}
.collapase-main {
    margin-bottom: 5px;
}
.collapsebg .tree-main {
    box-shadow: 0 2px 3px #d2d2d2bf;
    border: 1px solid #ebebeb;
}
.collapsebg ul li {
    padding-left: 1.7rem !important;
}
.collapsebg ul li:hover {
  background-color: #f6f6f6;
}

</style>